#include "mainwindow.h"
#include <QRect>

QMutex lock;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    camera(NULL),
    viewfinder(NULL),
    videoProbe(NULL),
    img(NULL),
    videoSurfaceFiter(NULL),
    videoWidget(NULL)
{
    camera = new QCamera(this);
    videoSurfaceFiter = new videoSurface(this);

    camera->setViewfinder(videoSurfaceFiter);
    camera->setCaptureMode(QCamera::CaptureViewfinder);

    videoProbe = new QVideoProbe(this);

    if (videoProbe->setSource(camera)) {
        // Probing succeeded, videoProbe->isValid() should be true.
        connect(videoProbe, SIGNAL(videoFrameProbed(QVideoFrame)),this, SLOT(receiver(QVideoFrame)));
    }

    camera->start();
    //camera->unlock();
}

void MainWindow::receiver(const QVideoFrame &frame)
{
    lock.tryLock();

    videoSurfaceFiter->present(frame);
    img = videoSurfaceFiter->getQImage();

    update();
    lock.unlock();
    //camera->unlock();
}

void MainWindow::paintEvent(QPaintEvent *event)
{    
    Q_UNUSED(event);

    //lock.lock();

    QPainter paint(this);
    QRect rect(0,0,this->width(),this->height());

    if (img != NULL)
    {
        paint.drawImage(rect,*img);
        emit videoProbe->flush();
    }

    //paint.drawPixmap(rect,);
    //lock.unlock();
}

MainWindow::~MainWindow()
{
    if (camera != NULL)
    {
        camera->stop();
    }

    if (videoProbe != NULL)
    {
        delete videoProbe;
        videoProbe = NULL;
    }

    if (viewfinder != NULL)
    {
        delete viewfinder;
        viewfinder = NULL;
    }

    if (videoSurfaceFiter != NULL)
    {
        delete videoSurfaceFiter;
        videoSurfaceFiter = NULL;
    }

    if (camera != NULL)
    {
        delete camera;
        camera = NULL;
    }

    if (img != NULL)
    {
        delete img;
        img = NULL;
    }
}
